package com.yue.springDemo.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yue.springDemo.business.bean.RegisterUser;
import com.yue.springDemo.business.bean.User;
import com.yue.springDemo.business.mapper.HelloMapper;
import com.yue.springDemo.business.service.UserService;
import com.yue.springDemo.framework.expection.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private HelloMapper helloMapper;

    @Override
    public void register(RegisterUser registerUser) throws BusinessException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("job_number", registerUser.getJobNumber());
        int hasUser = helloMapper.selectCount(wrapper);
        if (hasUser > 0) {
            throw new BusinessException("该工号已存在，请换一个");
        }

        User user = new User();
        user.setName(registerUser.getName());
        user.setJobNumber(registerUser.getJobNumber());
        user.setPassword(new BCryptPasswordEncoder().encode(registerUser.getPassword()));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        helloMapper.insert(user);
    }

    @Override
    public void resetAdmin() {
        User user = new User();
        user.setId("1");
        user.setName("admin");
        user.setJobNumber("admin");
        user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        user.setUpdateTime(new Date());
        helloMapper.updateById(user);
    }
}
